//
// Create by Zeng Yun on 2019/1/8
//

package member

import (
	"adai.design/jarvis/common/log"
	"crypto/tls"
	"encoding/json"
	"errors"
	"github.com/sideshow/apns2"
	"github.com/sideshow/apns2/certificate"
)

const (
	apnsTopic = "adai.design.home"
)

type APNSAlert struct {
	Title string `json:"title"`
	Body  string `json:"body"`
}

func (apns *APNSAlert) String() string {
	buf, _ := json.Marshal(apns)
	return string(buf)
}

var apnsCert = func() *tls.Certificate {
	cert, err := certificate.FromP12File("conf/apns.p12", "clouds")
	if err != nil {
		cert, err = certificate.FromP12File("../conf/apns.p12", "clouds")
	}
	if err != nil {
		log.Error("%v", err)
		return nil
	}
	return &cert
}()

func PushNotificationToMember(id string, aps *APNSAlert) error {
	account, err := accounts.FindById(id)
	if err != nil {
		return err
	}

	clients := account.findClients()
	if clients == nil {
		return errors.New("clients 404 not found")
	}

	for _, c := range clients.Clients {
		if (c.DevType != ClientTypePhone && c.DevType != ClientTypePad) || c.APNS == "" {
			continue
		}

		notification := &apns2.Notification{
			DeviceToken: c.APNS,
			Topic:       apnsTopic,
		}
		c.Badge += 1
		info := map[string]interface{}{
			"aps": map[string]interface{}{
				"alert": map[string]interface{}{
					"title": aps.Title,
					"body":  aps.Body,
				},
				"category": "GENERAL",
				"badge":    c.Badge,
				"sound":    "default",
			},
		}
		notification.Payload, _ = json.Marshal(info)
		client := apns2.NewClient(*apnsCert).Development()
		res, err := client.Push(notification)
		if err != nil {
			log.Error("result err: %s", err)
		} else {
			log.Debug("result code(%v) apnsId(%v) reason(%v)", res.StatusCode, res.ApnsID, res.Reason)
		}

	}
	clients.Save()
	return nil
}
